// Learn cc.Class:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html

/*
 * 主要控制类 
 * 重庆时时彩投注
 */
cc.Class({
    extends: cc.Component,

    properties: {
        rtShowAmount:cc.RichText,//投注信息
        edMutipleNum:cc.Label,
        pageList:[cc.Node],
        tgSelect:cc.Toggle,
        pvBet:cc.Node,
        labPlaying:cc.Label,
        spBetBg:cc.Node,
        tgMiss:cc.Node,
        numberKeysPre: cc.Prefab,  //键盘界面预制

        _curMoney:0,
        _curBetNum:0,
        _TipName:[],
        _curPage:0,
        _missList:[],
        _missData:[],

        BASEMONEY:2,//单价列表
        _keysOpen: false,  
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.node.on(cc.Node.EventType.TOUCH_START, function (event) {
            console.log('betssc TOUCH_START-' + this.node.name);  
        }.bind(this), this);
        this.node.on(cc.Node.EventType.MOUSE_DOWN, function (event) {
            console.log('betssc MOUSE_DOWN-' + this.node.name);  
        }.bind(this), this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, function (event) {
            console.log('betssc TOUCH_MOVE-'+ this.node.name);  
        }.bind(this), this);
        this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
            console.log('betssc TOUCH_END-'+ this.node.name);  
        }.bind(this), this);  
     },

    start () {
        this._pageEx = this.pvBet.getComponent("PageViewExt");
        if(this._pageEx == null)
        {
            ComponentsUtils.showTips("投注面板加载失败");
            return;
        }

        this._TipName = [
            "大小单双",
            "一星",
            "二星",
            "三星",
            "五星"
        ]; 
        this._playCode = [
            [DEFINE.LOTTERY_RULE.ssc_cq_bxds],
            [DEFINE.LOTTERY_RULE.ssc_cq_zhione],
            [DEFINE.LOTTERY_RULE.ssc_cq_zhitwo,DEFINE.LOTTERY_RULE.ssc_cq_zutwo],
            [DEFINE.LOTTERY_RULE.ssc_cq_zhithree,DEFINE.LOTTERY_RULE.ssc_cq_zuthree,DEFINE.LOTTERY_RULE.ssc_cq_zusix],
            [DEFINE.LOTTERY_RULE.ssc_cq_zhifive]//,DEFINE.LOTTERY_RULE.ssc_cq_tongfive
        ]; 

        this._missList = [false,false,false,false,false];

        this._missData = [[],[],[],[],[]];
     
        this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
            console.log('bet_ssc_pop node  TOUCH_END');
            var contentRect = this.spBetBg.getBoundingBoxToWorld();
            var touchLocation = event.getLocation();
            contentRect.x = contentRect.x -20;
            contentRect.width = 1080;
            if(cc.rectContainsPoint(contentRect, touchLocation) == false){//关闭投注界面
                this.onClose();
            }
        }, this);

        window.Notification.on("updateTgSelect",function(data){
            this.updateTgSelect(data);
        },this);

    },

    init:function(lotteryId){
       // cc.log("彩种："+lotteryId);
    },

    //设置金额
    setMoney:function(mon){
        this._curMoney = mon;
    },

    //得到金额
    getMoney:function(){
        return this._curMoney;
    },

    //设置注数
    setBetNum:function(num){
        this._curBetNum = num;
    },

    //得到注数
    getBetNum:function(){
        return this._curBetNum;
    },

    //设置倍数
    setMutipleAmount:function(mutiple){
         this.edMutipleNum.string = mutiple;
    },    

    //获取当前倍数
    getMutipleAmount:function(){
        var amount = parseInt(this.edMutipleNum.string);
        if(isNaN(amount)){ 
            return 1;
        }else{
            return amount;
        }        
    },

    onTextBegan: function(){
        this.emptyNode =this.node.getChildByName('content').getChildByName('Node');
        if(!this.emptyNode.getChildByName('public_numberKeys_pop')){  //当键盘存在，就不必创建
            this.KeysPre =cc.instantiate(this.numberKeysPre);
            this.emptyNode.addChild(this.KeysPre);
            var Callback = function(data){
            this.onEditBoxMutipleChanged(data);
            }.bind(this);
            this.KeysPre.getComponent(this.KeysPre.name).init(Callback);
            this.KeysPre.getComponent(this.KeysPre.name).onShow();  //显示键盘界面  
        }else{
            this.KeysPre.getComponent(this.KeysPre.name).onShow();  //显示键盘界面      
        }
        this._keysOpen =true;  //键盘开启
    },

    //手动倍数
    onEditBoxMutipleChanged:function(text) {
        var amount =text;
        if(amount =='ok'){
            // this.emptyNode.getComponent(cc.Layout).enabled = false; 
            this.KeysPre.getComponent(this.KeysPre.name).onClose();  //清除键盘界面 
            this._keysOpen =false;   
            if(this.edMutipleNum.string == null || this.edMutipleNum.string == "")
            {
                this.edMutipleNum.string = "1";
            }
        }else if(amount =='-'){
            if(this.edMutipleNum.string.length > 0){
                this.edMutipleNum.string =this.edMutipleNum.string.slice(0,-1);  
            }        
        }else{
            this.edMutipleNum.string += amount;   
            if(this.edMutipleNum.string.length>5){   //只能输入5位
                this.edMutipleNum.string =this.edMutipleNum.string.slice(0,5);  
            }   
        }
        
        this.showAmount(this.getBetNum());
    },

    //显示投注信息
    showAmount:function(bet){
        var mut = this.getMutipleAmount();
        var money = mut*bet*this.BASEMONEY;
        this.setMoney(money);
        this.setBetNum(bet);
        this.rtShowAmount.string = "共"+bet+"注"+ mut +"倍" + money+"元宝";
    },

    //清空选择
    clearCurSel:function(){
        this.setMutipleAmount(1);
        this.showAmount(1);
    },

    //选择清空切换
    onSelectCallBack:function(toggle){
        var curpage = this.pageList[this._pageEx.getCurrentPageIndex()];
        if(curpage == null || curpage.getComponent(curpage.name) == null)
            return;
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this.clearCurSel();
            curpage.getComponent(curpage.name).clearAllBetRecord();
        }
        else
        {
            this.clearCurSel();
            curpage.getComponent(curpage.name).randomSelectCallBack();
        }
    },

    onRightPage:function(event,customEventData){
        this._curPage = this._pageEx.getCurrentPageIndex()+1 == this._pageEx.getPages().length ? 0 : this._pageEx.getCurrentPageIndex()+1;
        this._pageEx.scrollToPage(this._curPage);
        this.labPlaying.string = this._TipName[this._curPage];
        this.tgMiss.getComponent(cc.Toggle).isChecked = this._missList[this._curPage];
    },

    onLeftPage:function(event,customEventData){
        this._curPage = this._pageEx.getCurrentPageIndex()-1 <0 ? this._pageEx.getPages().length-1 : this._pageEx.getCurrentPageIndex()-1;
        this._pageEx.scrollToPage(this._curPage);
        this.labPlaying.string = this._TipName[this._curPage];
        this.tgMiss.getComponent(cc.Toggle).isChecked = this._missList[this._curPage];
    },

    //遗漏
    onMiss:function(toggle, customEventData){
        var curpage = this.pageList[this._pageEx.getCurrentPageIndex()];
        if(curpage == null || curpage.getComponent(curpage.name) == null)
            return;

        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            if(this._missData[this._curPage].length>0)
            {
                this._missList[this._pageEx.getCurrentPageIndex()] = true;
                curpage.getComponent(curpage.name).showMiss(this._missData[this._curPage]);
            }
            else
            {
                var getMiss = function(num){
                    if(num < this._playCode[this._curPage].length)
                    {
                        let count = num+1;
                        var recv = function(ret){  
                            ComponentsUtils.unblock();   
                            var temparr = [];
                            if(ret.Code === 0)
                            {
                                temparr = ret.Data;
                                try {
                                    var obj = eval('('+temparr+')');
                                    if(obj["o"].length>3)
                                    {
                                        this._missData[this._curPage].push(obj["o"]);
                                    }
                                    else
                                    {
                                        for(let i=0;i<obj["o"].length;i++)
                                        {
                                            this._missData[this._curPage].push(obj["o"][i]);
                                        }
                                    }
                                    getMiss(count);
                                } catch (error) {
                                    this._missData[this._curPage].length = 0;
                                    toggle.getComponent(cc.Toggle).isChecked = false;
                                    return;
                                }
                            }
                            else
                            {
                                ComponentsUtils.showTips(ret.Msg);  
                                toggle.getComponent(cc.Toggle).isChecked = false;
                            }
                            
                        }.bind(this);
                        var data = {
                            LotteryCode:DEFINE.LOTTERY_ID.SSC_CQ,
                            IsuseName:"1",
                            PlayCode:this._playCode[this._curPage][num],
                            TopCount:100
                        }
                        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETLOTTERYMISS, data, recv.bind(this),"POST");  
                        ComponentsUtils.block(); 
                    }
                    else
                    {
                        curpage.getComponent(curpage.name).showMiss(this._missData[this._curPage]);
                    }
                }.bind(this);
                getMiss(0);
            }
        }
        else
        {
            this._missList[this._pageEx.getCurrentPageIndex()] = false;
            curpage.getComponent(curpage.name).hideMiss();
        }
    },

    pageScrollEvent:function(sender, eventType) {
        //翻页事件
        if(this._curPage != this._pageEx.getCurrentPageIndex())
        {
            this._curPage = this._pageEx.getCurrentPageIndex();
            this.labPlaying.string = this._TipName[this._curPage];
            this.tgMiss.getComponent(cc.Toggle).isChecked = this._missList[this._curPage];
        }
        return;
    },

    updateTgSelect:function(ischeck){
        this.tgSelect.getComponent(cc.Toggle).isChecked = ischeck;
    },

      
    //投注信息组合
    dataToJson:function(data){
        //组合
        var obj = new Object(); 
        obj.PlayCode = data.PlayCode; 

        var arry = [];
        var numArrays = {
            "Multiple":this.getMutipleAmount(),
            "Bet":this.getBetNum(),
            "isNorm":1,
            "Number":data.num
        };
        arry.push(numArrays);
        obj.Data = arry;

        var objs = [];
        objs.push(obj);
        var json = JSON.stringify(objs);
        cc.log("提交订单：" + json);
        return json;
    },

    //付款
    onPayBtn:function(){
        if(this.edMutipleNum.string == null || this.edMutipleNum.string == "")
        {
            this.edMutipleNum.string = "1";
        }
        if(this.getMoney() <= 0)
        {
            ComponentsUtils.showTips("投注不能为空");
            return;
        }
        
        var curpage = this.pageList[this._pageEx.getCurrentPageIndex()];
        if(curpage == null || curpage.getComponent(curpage.name) == null)
        {
            ComponentsUtils.showTips("投注单生成错误");
            return;
        }

        var dataobj =  curpage.getComponent(curpage.name).dataObj();
        var data = {
            lotteryId:DEFINE.LOTTERY_ID.SSC_CQ,//彩种id
            dataBase:this.dataToJson(dataobj),//投注信息
            otherBase:"",//追加
            money:this.getMoney(),
            buyType: 0,//追号
            betType: DEFINE.BET_PAY_TYPE.NORMAL//投注类型
        }
        window.Notification.emit("BET_ONPAY",data);

        //关闭键盘界面
        if(!this._keysOpen){
            return;
        }
        if(this.KeysPre){  
            this.KeysPre.getComponent(this.KeysPre.name).onClose();  //清除键盘界面 
            this._keysOpen =false;
        }
    },

    onDestroy:function(){
        window.Notification.offType("updateTgSelect");
    },

    onClose:function(){
        window.Notification.emit("BET_ONCLOSE","");
        //关闭键盘界面
        if(!this._keysOpen){
            return;
        }
        
        if(this.KeysPre){  
            this.KeysPre.getComponent(this.KeysPre.name).onClose();  //清除键盘界面 
            this._keysOpen =false;
        } 
    },

    // update (dt) {},
});
